<?php
namespace trade\common\gather;

use Yii;
use GatewayWorker\Lib\Gateway;
use trade\common\DBTool;
use trade\common\service\KlineService;
use think\facade\Db;
class Gather
{
	protected static $symbols = [];
    protected static $format  = [
        'ask' => 0,//卖一价
        'asm' => 0,//卖一量
        'bid' => 0,//买一价
        'bim' => 0,//买一量
        'ask2' => 0,//卖二价
        'asm2' => 0,//卖二量
        'bid2' => 0,//买二价
        'bim2' => 0,//买二量
        'ask3' => 0,//卖三价
        'asm3' => 0,//卖三量
        'bid3' => 0,//买三价
        'bim3' => 0,//买三量
        'ask4' => 0,//卖四价
        'asm4' => 0,//卖四量
        'bid4' => 0,//买四价
        'bim4' => 0,//买四量
        'ask5' => 0,//卖五价
        'asm5' => 0,//卖五量
        'bid5' => 0,//买五价
        'bim5' => 0,//买五量
        'open' => 0,//开盘价
        'close' => 0,//收盘价
        'js'    => 0,//结算价
        'nv'    => 0,//最新成交量
        'high' => 0,//最高价
        'low' => 0,//最低价
        'wave' => 0,//涨幅
        'price' => 0,//当前价
        'volume' => 0,//交易量
        'position' => 0,//持仓量
        'cleaning' => 0,//平仓量
        'limit_up' => 0,//涨停
        'limit_dn' => 0,//跌停
        'close_past' => 0,
        'position_past' => 0,
        'cleaning_past' => 0,
        'digit'         => 4,
    ];

    /**
     * 监听实时价格
     **/
    public function _listen($symbol,$prex){
        if( !empty($symbol['ticket']) && !empty($symbol['ticket']['code']) && !empty($symbol['ticket']['ctm']) && !empty($symbol['ticket']['ctmfmt']) )
        {
            $kline = new KlineService();
            $kline->save($symbol['ticket'],$prex,function($ticket,$prex)use($symbol)
            {
                Gateway::sendToGroup($prex,json_encode(['event' => 'ticket', 'data' => $ticket]));
                (new GatherAliyun_TfFutures())->listen($symbol,$prex);
            });
        }
    }

    /**
     * 分段获取所有产品
     **/
    public function loadSymbol($table,$func,$chunk=10){

    	if( !empty($this->symbols) ){

    		$items = [];$count = 0;
    		foreach ( static::$symbols as $code => $item ){
    			$items[] = $item;$count++;
    			if( $count<10 ){
    				$func($items);
    			}else{
    				$items = [];$count = 0;
    			}
    		}
    	}else{
    		Db::table($table)->where("on_sale","=","on")->order('sort', 'asc')->chunk($chunk, function($items) use ($func){
    		    foreach($items as $item){
    				static::$symbols[ $item['code2'] ] = $item;
    			}
    			$func($items);
    		});
    	}
    }

}
